<template>
  <div class="add">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm">
      <div style="display: flex">
        <el-form-item label="任务类型" prop="type">
          <el-cascader v-model="ruleForm.type" :options="commonCascaderOptions" :props="propsCascader" clearable
            @expand-change="commonCascaderChange" @change="handleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="任务金额（元）" prop="price" style="margin-left: 30px">
          <el-input v-model="ruleForm.price" clearable placeholder="请输入任务金额"></el-input>
        </el-form-item>
      </div>

      <el-form-item label="任务名称" prop="name" v-if="formType == 0 || formType == 1">
        <el-input v-model="ruleForm.name" placeholder="请输入任务名称"></el-input>
      </el-form-item>

      <div v-if="formType == 0">
        <el-form-item label="任务描述" prop="text">
          <el-input type="textarea" :rows="4" v-model="ruleForm.text" placeholder="请输入任务描述"></el-input>
        </el-form-item>

        <div style="display: flex">
          <el-form-item label="联系方式1" prop="phone1">
            <el-input v-model="ruleForm.phone1" placeholder="请输入联系方式1"></el-input>
          </el-form-item>
          <el-form-item label="联系方式2" prop="phone2" style="margin-left: 30px">
            <el-input v-model="ruleForm.phone2" placeholder="请输入联系方式2"></el-input>
          </el-form-item>
        </div>

        <el-form-item label="任务步骤" prop="step" style="width: 70%">
          <wang-edit ref="wangEditorRef" v-if="editShow" :editorParams="ruleForm.editorParams" />
        </el-form-item>
      </div>

      <div v-if="formType == 1">
        <el-form-item label="工作日期" prop="workTime">
          <el-input v-model="ruleForm.workTime" placeholder="长期兼职，能工作一个月以上"></el-input>
        </el-form-item>

        <div style="display: flex">
          <el-form-item label="联系方式1" prop="phone1">
            <el-input v-model="ruleForm.phone1" placeholder="请输入手机号/微信号"></el-input>
          </el-form-item>
          <el-form-item label="联系方式2" prop="phone2" style="margin-left: 30px" placeholder="请输入手机号/微信号">
            <el-input v-model="ruleForm.phone2"></el-input>
          </el-form-item>
        </div>

        <el-form-item label="岗位要求" prop="step" style="width: 70%">
          <wang-edit ref="wangEditorRef" v-if="editShow" :editorParams="ruleForm.editorParams" />
        </el-form-item>
      </div>

      <div v-if="formType == 2">
        <div style="display: flex">
          <el-form-item label="任务名称" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入任务名称"></el-input>
          </el-form-item>

          <el-form-item label="合作类型" prop="cooperationType" style="margin-left: 30px" placeholder="请选择合作类型">
            <el-select v-model="ruleForm.cooperationType" multiple placeholder="请选择">
              <el-option v-for="item in cooperationTypeOptions" :key="item.taskClassifyId"
                :label="item.taskClassifyName" :value="item.taskClassifyId">
              </el-option>
            </el-select>
          </el-form-item>
        </div>

        <el-form-item label="合作区域" prop="address">
          <el-cascader v-model="ruleForm.address" :options="addressCascaderOptions" :props="addressCascader" clearable
            @change="addressChange"></el-cascader>

          <!-- <el-input
            v-model="ruleForm.address"
            placeholder="请输入合作区域"
          ></el-input> -->
        </el-form-item>

        <div style="display: flex">
          <el-form-item label="联系方式1" prop="phone1">
            <el-input v-model="ruleForm.phone1" placeholder="请输入手机号/微信号"></el-input>
          </el-form-item>
          <el-form-item label="联系方式2" prop="phone2" style="margin-left: 30px" placeholder="请输入手机号/微信号">
            <el-input v-model="ruleForm.phone2"></el-input>
          </el-form-item>
        </div>

        <el-form-item label="合作概述" prop="step" style="width: 70%">
          <wang-edit ref="wangEditorRef" v-if="editShow" :editorParams="ruleForm.editorParams" />
        </el-form-item>
      </div>

      <el-form-item>
        <div class="form-button">
          <div class="list" @click="addClose">取消</div>
          <div class="list" @click="addSave('ruleForm')">保存</div>
          <div class="list" @click="addissueSave('ruleForm')">保存并发布</div>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import WangEdit from "@/components/wangEditor/RichTextEditor.vue";

import {
  makeTaskClassifyList,
  makeTaskListId,
  makeTaskListAdd,
} from "@/api/make";

import { commonDistrictList } from "@/api/common";

var throttle = require("@/utils/throttle"); // 防抖
import {
  codeVerification
} from '@/utils/verify'

export default {
  components: {
    WangEdit,
  },

  data() {
    return {
      id: "",
      soucre: '',
      //----------
      taskObj: {},
      ruleForm: {
        type: [],
        //-----------------
        price: "",
        name: "",
        text: "",
        step: "",
        //--------------
        workTime: "",
        //--------
        address: "",
        phone1: "",
        phone2: "",
        projectName: "",
        //----------
        cooperationType: "",
        editorParams: {
          content: "", // 富文本内容
          placeholder: "请填写内容", // 富文本占位内容
          uploadImageUrl: "/file", // 富文本上传图片的地址
          height: "400px", // 富文本最小高度
          isDisabled: false, // 富文本是否禁用
        },
      },
      rules: {
        type: [{ required: true, message: "请选择任务类型", trigger: "blur" }],
        price: [{ required: true, message: "请输入任务金额", trigger: "blur" }],
        name: [
          { required: true, message: "请输入任务名称", trigger: "blur" },
        ],
        text: [{ required: true, message: "请输入任务描述", trigger: "blur" }],
        step: [{ required: true, message: "请输入任务步骤", trigger: "blur" }],
        //----
        address: [
          { required: true, message: "请选择合作区域", trigger: "blur" },
        ],
        //--------

        workTime: [
          { required: true, message: "请输入工作时间", trigger: "blur" },
        ],
        phone1: [
          { required: true, message: "请输入联系方式1", trigger: "blur" },
        ],
        phone2: [
          { required: true, message: "请输入联系方式2", trigger: "blur" },
        ],
        projectName: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        //--------
        cooperationType: [
          { required: true, message: "请选择合作类型", trigger: "blur" },
        ],
      },

      //----------------
      commonCascaderOptions: [],
      propsCascader: {
        value: "taskClassifyId",
        label: "taskClassifyName",
        children: "children",
        checkStrictly: true,
      },
      //------------

      cooperationTypeOptions: [],
      //-----------
      editShow: false,

      //----------------区分
      formType: 0,
      addressCascaderOptions: [],
      addressCascader: {
        value: "id",
        label: "text",
        children: "data",
      },
    };
  },
  created() {
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      this.formType = this.$route.query.soucre == 3 ? 1 : this.$route.query.soucre == 0 ? 0 : this.$route.query.soucre == 1 ? 0 : this.$route.query.soucre == 2 ? 2 : '';
    }

    if (this.$route.query.soucre == 2) {
      this.cooperationMet();
      this.commonDistrictListMet();

    }


    this.makeTaskClassifyListMet();



  },
  mounted() {
    this.editShow = true;
  },
  methods: {
    makeTaskListIdMet() {
      let params = this.id;

      makeTaskListId(params).then((res) => {
        if (res.errorCode == null) {
          res.resultData.taskPrice = Number(
            res.resultData.taskPrice / 100
          )


          this.ruleForm.price = res.resultData.taskPrice
          this.ruleForm.name = res.resultData.taskName
          this.ruleForm.phone1 = res.resultData.taskPhone.split(';')[0]
          this.ruleForm.phone2 = res.resultData.taskPhone.split(';')[1]


          if (this.formType == 0) {
            this.ruleForm.text = res.resultData.taskDesc
          }

          if (this.formType == 1) {
            this.ruleForm.workTime = res.resultData.workTime
          }

          if (this.formType == 2) {
            let array = []


            if (res.resultData.taskJoinClassifyList.length > 0) {
              res.resultData.taskJoinClassifyList.forEach((item, index) => {
                array.push(item.taskClassifyId)
              })
            }

            this.ruleForm.cooperationType = array
            this.ruleForm.address = [res.resultData.cooperationProvinceId, res.resultData.cooperationCityId, res.resultData.cooperationAreaId]
          }

          this.ruleForm.editorParams.content = res.resultData.taskContent;

          res.resultData.taskClassifyName = res.resultData.taskOneClassifyName
          if (res.resultData.taskOneClassifyId != null || res.resultData.taskOneClassifyId != '') {
            this.loadCascaderData(res.resultData.taskOneClassifyId);
          }




          this.taskObj = res.resultData;

          if (this.taskObj.taskOneClassifyId != '' && this.taskObj.taskOneClassifyId != null) {
            console.log('2', this.taskObj.taskOneClassifyId)
            this.ruleForm.type[0] = this.taskObj.taskOneClassifyId
          }
        }
      });
    },
    //----------------------------
    makeTaskClassifyListMet() {
      let params = {
        taskClassifyType: 0,
        fatherId: "",
        pageSize: 10000,
        pageNo: 1,
      };

      makeTaskClassifyList(params).then((res) => {
        if (res.errorCode == null) {
          res.resultData.taskClassifyList.forEach((item, index) => {
            item.children = [];
          });
          this.commonCascaderOptions = res.resultData.taskClassifyList;

          if (this.$route.query.id) {
            this.makeTaskListIdMet();
          }
        }
      });
    },
    commonCascaderChange(e) {
      this.loadCascaderData(e[0]);
    },
    loadCascaderData(id) {
      let params = {
        taskClassifyType: 0,
        fatherId: id,
        pageSize: 10000,
        pageNo: 1,
      };

      makeTaskClassifyList(params).then((res) => {
        if (res.errorCode == null) {
          let mockData = res.resultData.taskClassifyList;

          if (mockData.length > 0) {
            this.commonCascaderOptions.forEach((item, index) => {
              if (item.taskClassifyId == id) {
                item.children = mockData;
              }
            });
          } else {
            console.log("当前勾选", this.commonCascaderOptions);
            let num = 0;
            this.commonCascaderOptions.forEach((item, index) => {
              if (item.taskClassifyId == id) {
                num = id;
              }
            });

            this.ruleForm.cascader = [num];
          }



          if (this.taskObj.taskTwoClassifyId != '' && this.taskObj.taskTwoClassifyId != null) {
            this.commonCascaderOptions.forEach((info, num) => {
              if (info.taskClassifyId == this.taskObj.taskOneClassifyId) {
                info.children.forEach((item, index) => {
                  if (item.taskClassifyId == this.taskObj.taskTwoClassifyId) {
                    this.ruleForm.type[1] = this.taskObj.taskTwoClassifyId
                  } else {

                  }
                })
              }
            })
          }
        }
      });
    },
    handleChange(value) {
      console.log('获取value', value)


      this.ruleForm.type = value;
      this.commonCascaderOptions.forEach((item, index) => {
        if (item.taskClassifyId == value[0]) {
          this.taskObj = item;

          if (
            item.taskClassifyName == "线上任务" ||
            item.taskClassifyName == "线下任务"
          ) {
            this.formType = 0;
          } else if (item.taskClassifyName == "兼职任务") {
            this.formType = 1;
          } else if (item.taskClassifyName == "合作任务") {
            this.formType = 2;
            this.cooperationMet();
            this.commonDistrictListMet();
          }
        }
      });
    },

    cooperationMet() {
      let params = {
        taskClassifyType: 1,
        fatherId: "",
        pageSize: 10000,
        pageNo: 1,
      };

      makeTaskClassifyList(params).then((res) => {
        if (res.errorCode == null) {
          this.cooperationTypeOptions = res.resultData.taskClassifyList;
        }
      });
    },
    commonDistrictListMet() {
      let params = {};

      commonDistrictList(params).then((res) => {
        if (res.errorCode == null) {
          this.addressCascaderOptions = res.resultData;
        }
      });
    },
    //----------------------------

    //-------
    setHtml(html) {
      // 回显富文本框中内容
      let _this = this;
      this.$nextTick(() => {
        // 此处用来解决富文本编辑器未完全加载的问题
        setTimeout(() => {
          _this.$refs.wangEditorRef.setEditorHtml(html);
        }, 200);
      });
    },
    getHtml() { },

    addressChange(value) {
      console.log("获取勾选你的", value);
    },

    //-------------------------------------------------------------------------------------------
    addClose() {
      this.$router.push({
        path: "/make/task-list/task-list-surface",
      });
    },
    addSave: throttle.throttle(function (formName) {
      this.ruleForm.step =
        this.$refs.wangEditorRef.getEditorHtml() == "<p><br></p>"
          ? ""
          : this.$refs.wangEditorRef.getEditorHtml();

      //----------------
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let taskType =
            this.taskObj.taskClassifyName == "线下任务"
              ? 0
              : this.taskObj.taskClassifyName == "线上任务"
                ? 1
                : this.taskObj.taskClassifyName == "合作任务"
                  ? 2
                  : this.taskObj.taskClassifyName == "兼职任务"
                    ? 3
                    : "";

          let params = {};



          if (codeVerification(this.ruleForm.phone1) == false) {
            this.$message.error('请输入正确格式的联系方式1手机号！')
            return
          }

          if (codeVerification(this.ruleForm.phone2) == false) {
            this.$message.error('请输入正确格式的联系方式2手机号！')
            return
          }




          if (this.formType == 0) {
            params = {
              taskId: this.id,
              taskType: taskType,
              taskOneClassifyId: this.ruleForm.type[0],
              taskTwoClassifyId: this.ruleForm.type[1],
              taskName: this.ruleForm.name,
              taskDesc: this.ruleForm.text,
              taskPhone: this.ruleForm.phone1 + ";" + this.ruleForm.phone2,
              taskPrice: Number(this.ruleForm.price * 100),
              taskContent: this.ruleForm.step,
              status: 0,
            };
          } else if (this.formType == 1) {
            params = {
              taskId: this.id,
              taskType: taskType,
              taskOneClassifyId: this.ruleForm.type[0],
              taskTwoClassifyId: this.ruleForm.type[1],
              taskName: this.ruleForm.name,
              taskDesc: this.ruleForm.text,
              taskPhone: this.ruleForm.phone1 + ";" + this.ruleForm.phone2,
              taskPrice: Number(this.ruleForm.price * 100),
              taskContent: this.ruleForm.step,
              status: 0,
              //-----------
              workTime: this.ruleForm.workTime,
            };
          } else if (this.formType == 2) {
            let cooperationProvince = "";
            let cooperationCity = "";
            let cooperationArea = "";

            this.addressCascaderOptions.forEach((item, index) => {
              if (item.id == this.ruleForm.address[0]) {
                cooperationProvince = item.text;

                item.data.forEach((info, num) => {
                  if (info.id == this.ruleForm.address[1]) {
                    cooperationCity = info.text;

                    info.data.forEach((obj, num) => {
                      if (obj.id == this.ruleForm.address[2]) {
                        cooperationArea = obj.text;
                      }
                    });
                  }
                });
              }
            });

            let taskJoinClassifyList = [];
            // 数组对象（A）
            const arrValues = this.ruleForm.cooperationType;

            // 直接修改原数组
            this.cooperationTypeOptions.forEach((info) => {
              if (arrValues.includes(info.taskClassifyId)) {
                let obj = {
                  taskClassifyId: info.taskClassifyId,
                  taskClassifyName: info.taskClassifyName,
                };

                taskJoinClassifyList.push(obj);
              } else {
              }
            });

            params = {
              taskId: this.id,
              taskType: taskType,
              taskOneClassifyId: this.ruleForm.type[0],
              taskTwoClassifyId: this.ruleForm.type[1],
              taskName: this.ruleForm.name,
              taskDesc: this.ruleForm.text,
              taskPhone: this.ruleForm.phone1 + ";" + this.ruleForm.phone2,
              taskPrice: Number(this.ruleForm.price * 100),
              taskContent: this.ruleForm.step,
              status: 0,
              //------------
              cooperationProvinceId: this.ruleForm.address[0],
              cooperationCityId: this.ruleForm.address[1],
              cooperationAreaId: this.ruleForm.address[2],
              cooperationProvince: cooperationProvince,
              cooperationCity: cooperationCity,
              cooperationArea: cooperationArea,
              taskJoinClassifyList: taskJoinClassifyList,
            };
          }

          makeTaskListAdd(params).then((res) => {
            if (res.errorCode == null) {
              if (this.id == "") {
                this.$message.success("新增任务成功！");
              } else {
                this.$message.success("修改任务成功！");
              }

              setTimeout(() => {
                this.$router.push({
                  path: "/make/task-list/task-list-surface",
                });
              }, 1000);
            }
          });
        } else {
          return false;
        }
      });
    }, 2000),

    addissueSave: throttle.throttle(function (formName) {
      this.ruleForm.step =
        this.$refs.wangEditorRef.getEditorHtml() == "<p><br></p>"
          ? ""
          : this.$refs.wangEditorRef.getEditorHtml();

      //----------------
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let taskType =
            this.taskObj.taskClassifyName == "线下任务"
              ? 0
              : this.taskObj.taskClassifyName == "线上任务"
                ? 1
                : this.taskObj.taskClassifyName == "合作任务"
                  ? 2
                  : this.taskObj.taskClassifyName == "兼职任务"
                    ? 3
                    : "";

          let params = {};


          if (codeVerification(this.ruleForm.phone1) == false) {
            this.$message.error('请输入正确格式的联系方式1手机号！')
            return
          }

          if (codeVerification(this.ruleForm.phone2) == false) {
            this.$message.error('请输入正确格式的联系方式2手机号！')
            return
          }

          if (this.formType == 0) {
            params = {
              taskId: this.id,
              taskType: taskType,
              taskOneClassifyId: this.ruleForm.type[0],
              taskTwoClassifyId: this.ruleForm.type[1],
              taskName: this.ruleForm.name,
              taskDesc: this.ruleForm.text,
              taskPhone: this.ruleForm.phone1 + ";" + this.ruleForm.phone2,
              taskPrice: Number(this.ruleForm.price * 100),
              taskContent: this.ruleForm.step,
              status: 1,
            };
          } else if (this.formType == 1) {
            params = {
              taskId: this.id,
              taskType: taskType,
              taskOneClassifyId: this.ruleForm.type[0],
              taskTwoClassifyId: this.ruleForm.type[1],
              taskName: this.ruleForm.name,
              taskDesc: this.ruleForm.text,
              taskPhone: this.ruleForm.phone1 + ";" + this.ruleForm.phone2,
              taskPrice: Number(this.ruleForm.price * 100),
              taskContent: this.ruleForm.step,
              status: 1,
              //-----------
              workTime: this.ruleForm.workTime,
            };
          } else if (this.formType == 2) {
            let cooperationProvince = "";
            let cooperationCity = "";
            let cooperationArea = "";

            this.addressCascaderOptions.forEach((item, index) => {
              if (item.id == this.ruleForm.address[0]) {
                cooperationProvince = item.text;

                item.data.forEach((info, num) => {
                  if (info.id == this.ruleForm.address[1]) {
                    cooperationCity = info.text;

                    info.data.forEach((obj, num) => {
                      if (obj.id == this.ruleForm.address[2]) {
                        cooperationArea = obj.text;
                      }
                    });
                  }
                });
              }
            });

            let taskJoinClassifyList = [];
            // 数组对象（A）
            const arrValues = this.ruleForm.cooperationType;

            // 直接修改原数组
            this.cooperationTypeOptions.forEach((info) => {
              if (arrValues.includes(info.taskClassifyId)) {
                let obj = {
                  taskClassifyId: info.taskClassifyId,
                  taskClassifyName: info.taskClassifyName,
                };

                taskJoinClassifyList.push(obj);
              } else {
              }
            });

            params = {
              taskId: this.id,
              taskType: taskType,
              taskOneClassifyId: this.ruleForm.type[0],
              taskTwoClassifyId: this.ruleForm.type[1],
              taskName: this.ruleForm.name,
              taskDesc: this.ruleForm.text,
              taskPhone: this.ruleForm.phone1 + ";" + this.ruleForm.phone2,
              taskPrice: Number(this.ruleForm.price * 100),
              taskContent: this.ruleForm.step,
              status: 1,
              //------------
              cooperationProvinceId: this.ruleForm.address[0],
              cooperationCityId: this.ruleForm.address[1],
              cooperationAreaId: this.ruleForm.address[2],
              cooperationProvince: cooperationProvince,
              cooperationCity: cooperationCity,
              cooperationArea: cooperationArea,
              taskJoinClassifyList: taskJoinClassifyList,
            };
          }

          makeTaskListAdd(params).then((res) => {
            if (res.errorCode == null) {
              if (this.id == "") {
                this.$message.success("新增任务成功！");
              } else {
                this.$message.success("修改任务成功！");
              }

              setTimeout(() => {
                this.$router.push({
                  path: "/make/task-list/task-list-surface",
                });
              }, 1000);
            }
          });
        } else {
          return false;
        }
      });
    }, 2000)
  },
};
</script>

<style lang="less" scoped>
.add {
  width: 80%;

  .demo-ruleForm {
    /deep/ .el-input {
      width: 400px;
    }

    /deep/ .el-textarea {
      width: 400px;
    }

    /deep/ .el-input__inner {
      width: 400px;
    }

    .form-button {
      display: flex;
      align-items: center;

      /deep/ .el-form-item__content {
        line-height: 0;
      }

      .list {
        background: #3da8f5;
        color: #fff;
        font-size: 16px;
        margin-right: 20px;
        border-radius: 5px;
        padding: 0 20px;
        box-sizing: border-box;
        height: 35px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
      }

      .list:first-child {
        background: #808080;
      }
    }
  }
}
</style>